#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>

#define PORT 7777
#define BUFFER_SIZE 4096

int main()
{
    int server_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    char buffer[BUFFER_SIZE];
    char filename[256];

    /* 创建socket */
    if ((server_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    /* 配置服务器地址 */
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    /* 绑定socket */
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    printf("UDP Server listening on port %d...\n", PORT);

    while (1)
    {
        /* 接收文件名 */
        memset(filename, 0, sizeof(filename));
        if (recvfrom(server_fd, filename, sizeof(filename), 0,
                     (struct sockaddr *)&client_addr, &client_addr_len) == -1)
        {
            perror("recv filename failed");
            continue;
        }

        printf("Receiving file %s from %s:%d\n", filename,
               inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

        /* 创建文件 */
        int file_fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (file_fd == -1)
        {
            perror("open file failed");
            continue;
        }

        /* 接收文件内容 */
        memset(buffer, 0, BUFFER_SIZE);
        ssize_t bytes_received;
        int timeout_count = 0;

        /* 设置超时 */
        struct timeval timeout;
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        setsockopt(server_fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));

        while (1)
        {
            bytes_received = recvfrom(server_fd, buffer, BUFFER_SIZE, 0,
                                      (struct sockaddr *)&client_addr, &client_addr_len);
            if (bytes_received > 0)
            {
                write(file_fd, buffer, bytes_received);
                timeout_count = 0;
            }
            else
            {
                // 超时，可能传输完成
                timeout_count++;
                if (timeout_count > 3)
                {
                    break;
                }
            }
        }

        close(file_fd);
        printf("File %s received successfully\n", filename);
    }

    close(server_fd);
    return 0;
}